package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
	private final OrderMapper orderMapper;
	private final OrderDetailMapper orderDetailMapper;
	private final ShoppingCartMapper shoppingCartMapper;
	private final UserMapper userMapper;
	private final AddressBookMapper addressBookMapper;
	private final WeChatPayUtil weChatPayUtil;
	private final WebSocketServer webSocketServer;
	
	public OrderServiceImpl(OrderMapper orderMapper, OrderDetailMapper orderDetailMapper, ShoppingCartMapper shoppingCartMapper,
	                        UserMapper userMapper, AddressBookMapper addressBookMapper, WeChatPayUtil weChatPayUtil,
	                        WebSocketServer webSocketServer) {
		this.orderMapper = orderMapper;
		this.orderDetailMapper = orderDetailMapper;
		this.shoppingCartMapper = shoppingCartMapper;
		this.userMapper = userMapper;
		this.addressBookMapper = addressBookMapper;
		this.weChatPayUtil = weChatPayUtil;
		this.webSocketServer = webSocketServer;
	}
	
	/**
	 * 用户下单
	 *
	 * @param ordersSubmitDTO
	 * @return
	 */
	@Transactional
	public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
		//异常情况的处理（收货地址为空、购物车为空）
		AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
		if (addressBook == null) {
			throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
		}
		
		Long userId = BaseContext.getCurrentId();
		ShoppingCart shoppingCart = new ShoppingCart();
		shoppingCart.setUserId(userId);
		
		//查询当前用户的购物车数据
		List<ShoppingCart> shoppingCartList = shoppingCartMapper.getCart(shoppingCart);
		if (shoppingCartList == null || shoppingCartList.size() == 0) {
			throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
		}
		
		//构造订单数据
		Orders order = new Orders();
		BeanUtils.copyProperties(ordersSubmitDTO, order);
		order.setPhone(addressBook.getPhone());
		order.setAddress(addressBook.getDetail());
		order.setConsignee(addressBook.getConsignee());
		order.setNumber(String.valueOf(System.currentTimeMillis()));
		order.setUserId(userId);
		order.setStatus(Orders.PENDING_PAYMENT);
		order.setPayStatus(Orders.UN_PAID);
		order.setOrderTime(LocalDateTime.now());
		
		//向订单表插入1条数据
		orderMapper.insert(order);
		
		//订单明细数据
		List<OrderDetail> orderDetailList = new ArrayList<>();
		for (ShoppingCart cart : shoppingCartList) {
			OrderDetail orderDetail = new OrderDetail();
			BeanUtils.copyProperties(cart, orderDetail);
			orderDetail.setOrderId(order.getId());
			orderDetailList.add(orderDetail);
		}
		
		//向明细表插入n条数据
		orderDetailMapper.insertBatch(orderDetailList);
		
		//清理购物车中的数据
		shoppingCartMapper.deleteByUserId(userId);
		
		//封装返回结果
		
		return OrderSubmitVO.builder()
				.id(order.getId())
				.orderNumber(order.getNumber())
				.orderAmount(order.getAmount())
				.orderTime(order.getOrderTime())
				.build();
	}
	
	/**
	 * 订单支付
	 *
	 * @param ordersPaymentDTO
	 * @return
	 */
	public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
		// 当前登录用户id
		Long userId = BaseContext.getCurrentId();
		User user = userMapper.getById(userId);
		
		//调用微信支付接口，生成预支付交易单
		JSONObject jsonObject = weChatPayUtil.pay(
				ordersPaymentDTO.getOrderNumber(), //商户订单号
				new BigDecimal("0.01"), //支付金额，单位 元
				"苍穹外卖订单", //商品描述
				user.getOpenid() //微信用户的openid
		);
		
		if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
			throw new OrderBusinessException("该订单已支付");
		}
		
		OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
		vo.setPackageStr(jsonObject.getString("package"));
		
		return vo;
	}
	
	/**
	 * 支付成功，修改订单状态
	 *
	 * @param outTradeNo
	 */
	public void paySuccess(String outTradeNo) {
		// 当前登录用户id
		Long userId = BaseContext.getCurrentId();
		
		// 根据订单号查询当前用户的订单
		Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);
		
		// 根据订单id更新订单的状态、支付方式、支付状态、结账时间
		Orders orders = Orders.builder()
				.id(ordersDB.getId())
				.status(Orders.TO_BE_CONFIRMED)
				.payStatus(Orders.PAID)
				.checkoutTime(LocalDateTime.now())
				.build();
		
		orderMapper.update(orders);
		
		Map<Object, Object> map = new HashMap<>();
		map.put("type", 1);//消息类型，1表示来单提醒
		map.put("orderId", orders.getId());
		map.put("content", "订单号：" + outTradeNo);
		
		//通过WebSocket实现来单提醒，向客户端浏览器推送消息
		webSocketServer.sendToAllClient(JSON.toJSONString(map));
	}
	
	public void reminder(Long id) {
		// 查询订单是否存在
		Orders orders = orderMapper.getById(id);
		if (orders == null) {
			throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
		}
		
		//基于WebSocket实现催单
		Map<Object, Object> map = new HashMap<>();
		map.put("type", 2);//2代表用户催单
		map.put("orderId", id);
		map.put("content", "订单号：" + orders.getNumber());
		webSocketServer.sendToAllClient(JSON.toJSONString(map));
	}
	
	
	/**
	 * TODO:前端无显示, 原因未知
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public Result historyOrders(OrdersPageQueryDTO dto) {
		if (dto.getPage() == null) {
			dto.setPage(1);
		}
		if (dto.getPageSize() == null) {
			dto.setPageSize(5);
		}
		PageHelper.startPage(dto.getPage(), dto.getPageSize());
		dto.setUserId(BaseContext.getCurrentId());
		Page<Orders> page = orderMapper.getUserOrderList(dto);
		
		List<OrderVO> list = new ArrayList<>();
		
		// 查询出订单明细，并封装入OrderVO进行响应
		if (page != null && page.getTotal() > 0) {
			for (Orders orders : page.getResult()) {
				Long orderId = orders.getId();// 订单id
				
				// 查询订单明细
				List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
				
				OrderVO orderVO = new OrderVO();
				BeanUtils.copyProperties(orders, orderVO);
				List<String> dishes = new ArrayList<>();
				orderDetails.forEach(detail -> dishes.add(detail.getName()));
				orderVO.setOrderDishes(StringUtils.join(dishes, ","));
				orderVO.setOrderDetailList(orderDetails);
				
				list.add(orderVO);
			}
		}
		return Result.success(new PageResult(page.getTotal(), list));
	}
}
